package com.sibu.yx.promotion.admin.web.support.model;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.doubo.common.model.response.CommonResponse;
import com.sibu.yx.promotion.persistence.dto.UserPrincipal;
import com.sibu.yx.promotion.persistence.model.sys.SysUser;
import com.sibu.yx.promotion.persistence.util.SpringUtil;
import com.sibu.yx.promotion.service.sys.SysUserService;


public class MyShiroRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return super.supports(token);
    }

    /**
     * 获取用户角色和权限
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        SysUserService userService = SpringUtil.getBean(SysUserService.class);
        CommonResponse<SysUser> userResponseCommonResponse = userService.selectUser(userName);
        if (!userResponseCommonResponse.isSuccess()) {
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        SysUser user = userResponseCommonResponse.getResult();
        if (user.getLocked()) {
            throw new LockedAccountException("账号已被锁定,请联系管理员！");
        }
        if (user.getDeleteFlag()) {
            throw new IncorrectCredentialsException("账号已经删除");
        }
        UserPrincipal userPrincipal = new UserPrincipal();
        userPrincipal.setUserName(userName);
        userPrincipal.setUid(user.getId());
        userPrincipal.setRoleIds(user.getRoleIds());
        return new SimpleAuthenticationInfo(userPrincipal, password, getName());
    }
}
